package cn.tedu.straw.portal.controller;


import cn.tedu.straw.commons.dto.AnswerDTO;

import cn.tedu.straw.commons.model.Answer;

import cn.tedu.straw.commons.security.UserInfo;
import cn.tedu.straw.portal.service.IAnswerService;
import cn.tedu.straw.portal.service.ex.ParameterValidationException;
import cn.tedu.straw.commons.vo.AnswerVO;
import cn.tedu.straw.commons.vo.R;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2020-07-28
 */
@RestController
@RequestMapping("/v1/answers")
public class AnswerController {

    @Autowired
    private IAnswerService answerService;

    @RequestMapping("/post")
    public R<Answer> post(@Validated AnswerDTO answerDTO, BindingResult bindingResult, @AuthenticationPrincipal UserInfo userInfo){
        if (bindingResult.hasErrors()){
            String message = bindingResult.getFieldError().getDefaultMessage();
            throw new ParameterValidationException(message);
        }
        Answer answer = answerService.post(answerDTO, userInfo.getId(), userInfo.getNickname());
        return R.ok(answer);

    }

    //http://localhost:8088/api/v1/answers/question/16
    @GetMapping("/question/{questionId}")
    public R<List<AnswerVO>> getListByQuestion(@PathVariable("questionId") Integer questionId){
        return R.ok(answerService.getListByQuestion(questionId));
    }

    // http://localhost:8080/api/v1/answers/update/{id}?content=Hello,Kafka!!!
    @RequestMapping("/update/{id}")
    public R<Answer> update(@PathVariable("id") Integer id, String content, @AuthenticationPrincipal UserInfo userInfo) {
        Answer answer = answerService.update(id, userInfo.getId(),content,  userInfo.getType());
        return R.ok(answer);
    }


    @RequestMapping("/delete/{id}")
    public R<Answer> delete(@PathVariable("id") Integer id, @AuthenticationPrincipal UserInfo userInfo){
        Answer answer=answerService.delete(id, userInfo.getId(), userInfo.getType());
        return R.ok(answer);
    }

    @RequestMapping("/my")
    public R<PageInfo<Answer>> get(Integer page, @AuthenticationPrincipal UserInfo userInfo){
        if (page==null||page<1){
            page=1;
        }
        PageInfo<Answer> answer = answerService.getAnswer(userInfo.getId(), page);
        return R.ok(answer);
    }

}
